package com.gruuf.done;

import com.gruuf.done.model.Task;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class MailService {

    public void sendMail(Task task) {
        try {
            send(task);
        } catch (Exception e) {
            throw new GruufException(e);
        }
    }

    private void send(Task task) throws MessagingException, UnsupportedEncodingException {
        Properties props = new Properties();
        Session session = Session.getDefaultInstance(props, null);
        Message msg = new MimeMessage(session);
        msg.setFrom(createFrom());
        msg.addRecipient(Message.RecipientType.TO, createTo());
        msg.setSubject(createSubject(task));
        msg.setText(createBody(task));
        Transport.send(msg);
    }

    private InternetAddress createTo() throws UnsupportedEncodingException {
        return new InternetAddress("lukasz.lenart@javarsovia.pl", "Lukasz Lenart");
    }

    private String createSubject(Task task) {
        return "[DONE] New Task: " + task.getName();
    }

    private InternetAddress createFrom() throws UnsupportedEncodingException {
        return new InternetAddress("lukasz.lenart@googlemail.com", "Gruuf DoneApplication");
    }

    private String createBody(Task task) {
        return "New task created!\r\n\r\n" + task;
    }

}
